package com.ruoyi.expert.service.impl;

import com.ruoyi.expert.mapper.FileMapper;
import com.ruoyi.expert.utils.DownloadFileUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.ruoyi.expert.service.FileService;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author 程家伟
 * Date 2022/3/1 20:08
 * Email 3497357686@qq.com
 */

@Service
public class FileServiceImpl implements FileService {
    @Value("${file.url}")
    private String fileUrl;
    //文本文件存储文件夹
    private final static String TXT_PATH="txt";
    //图片文件存储文件夹
    private final static String IMAGE_PATH="image";
    //pdf文件存储文件夹
    private final static String PDF_PATH="pdf";
    //其他文件存储文件夹
    private final static String OTHER_PATH="other";

    @Autowired
    private FileMapper fileMapper;


    /**
     * 文件上传功能
     */
    @Override
    public boolean upload(int id,String from ,MultipartFile file) {
        if (file != null){
            //获取文件名
            String filename = file.getOriginalFilename();

            if (filename !=null){
                //截取文件后缀名
                String type = filename.substring(filename.lastIndexOf(".")+1);
                //获取文件存储地址
                String filePath = getFilePath(type)+File.separator+getFilename(id,from)+"."+type;
                File loadFile = new File(filePath);
                try {
                    if (!loadFile.getParentFile().exists()){
                        loadFile.getParentFile().mkdirs();
                    }
                    file.transferTo(loadFile);
                    storageUrl(id,type,from,filePath);
                    return true;
                } catch (IOException e) {
                    return false;
                }
            } else return false;
        } else return false;
    }

    /**
     * 获取文件存储文件夹
     */
    @Override
    public String getFilePath(String type) {
        String path ;
        switch (type){
            //文本文件保存
            case "txt":
            case "docx":
            case "doc":
                path=fileUrl+ File.separator+TXT_PATH;
                break;
            //图片文件保存
            case "bmp":
            case "png":
            case "gif":
            case "webp":
            case "jpeg":
            case "jpg":
            case "psd":
                path=fileUrl+File.separator+IMAGE_PATH;
                break;
            //pdf文件保存
            case "pdf":
                path=fileUrl+File.separator+PDF_PATH;
                break;
            //文件类型未知，存入文本文件夹
            default:
                path=fileUrl+File.separator+OTHER_PATH;
        }
        return path;
    }

    /**
     * 获取文件名
     */
    @Override
    public String getFilename(int id, String from) {
        String filename ;
        String date = DateFormatUtils.format(new Date(),"yyyyMMdd");
        String s = RandomStringUtils.randomAlphanumeric(10);
        filename = id+"_"+from+"_"+date+"_"+s;
        return filename;
    }

    /**
     * 将文件的url存入对应的表中
     */
    @Override
    public void storageUrl(int id,String type, String from, String url) {
        String filePath = getFilePath(type);
        if (filePath.equals(fileUrl + File.separator + IMAGE_PATH)){
            fileMapper.insertImage(url,id,from);
        }else {
            fileMapper.insertFile(url,id,from);
        }
    }

    /**
     * 下载word文件
     */
    @Override
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        String from = request.getParameter("from");
        String wordUrl = fileMapper.getWordUrl(id, from);
        String type = wordUrl.substring(wordUrl.lastIndexOf(".")+1);
        File file = new File(wordUrl);
        String filename = "文档"+"."+type;
        DownloadFileUtil.downloadFile(filename,file,response,request);
    }

    /**
     *图片预览
     */
    @Override
    public List<String> viewPicture(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        String from = request.getParameter("from");
        List<String> imageUrl = fileMapper.getImageUrl(id, from);
        List<String> list =new ArrayList<String>();
        for (String value : imageUrl) {
            String imageBinary = getImageBinary(value);
            list.add(imageBinary);
        }
        return list;
    }

    /**
     *删除文本文件
     */
    @Override
    public boolean deleteWordFile(int id, String from) {
        String wordUrl = fileMapper.getWordUrl(id, from);
        File file = new File(wordUrl);
        fileMapper.deleteWordFile(id, from);
        return file.delete();
    }


    /**
     *删除图片文件
     */
    @Override
    public void deleteImage(int id, String from) {
        List<String> ImageUrl = fileMapper.getImageUrl(id, from);
        if (ImageUrl != null){
            for (String s : ImageUrl) {
                File file = new File(s);
                fileMapper.deleteImage(s);
                file.delete();
            }
        }
    }

    /**
     * 将图片转换为二进制
     */
    @Override
    public String getImageBinary(String url) {
        BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        File file = new File(url);
        BufferedImage bi;
        try {
            bi = ImageIO.read(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();

            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getImageType(String url) {
        return url.substring(url.lastIndexOf(".")+1);
    }

    @Override
    public List<String> getTypeLiat(HttpServletRequest request) {
        int id = Integer.parseInt(request.getParameter("id"));
        String from = request.getParameter("from");
        List<String> imageUrl = fileMapper.getImageUrl(id, from);
        List<String> list =new ArrayList<String>();
        for (String value : imageUrl) {
             list.add(getImageType(value));
        }
        return list;
    }


}
